package servlet;

import bean.User;
import bean.attendance;
import dao.impl.UserDaoImpl;
import dao.impl.attendanceDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author guoxiuwei
 * @Date 2020/8/17 19:36
 * @Title
 */
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //防止中文乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //获取页面传来的数据
        String uname = request.getParameter("UserName");
        String upwd = request.getParameter("UserPassword");

        //System.out.println(uname+"     "+upwd);
        boolean isSuccess = new UserDaoImpl().login(uname, upwd);
        if (isSuccess){
            User user=new UserDaoImpl().FindUid(uname);
            //为当前用户创建一个session
            HttpSession session = request.getSession();
            session.setAttribute("us",user);


            int uid=user.getUid();
            this.getServletContext().setAttribute("userid",uid);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateNowStr = sdf.format(date);//当前时间

            /*
            * 查询是否打卡
            * */
            attendance at=new attendanceDaoImpl().Finduiddatetime(uid,dateNowStr);
            if (at==null){
                int i=new attendanceDaoImpl().att_datetime(uid,dateNowStr);
                int rights=user.getRights();
                request.setAttribute("rights",rights);
                //request.getRequestDispatcher("nav.jsp").forward(request,response);
                request.getRequestDispatcher("manager.jsp").forward(request,response);
            }else {
                int rights=user.getRights();
                request.setAttribute("rights",rights);
                //request.getRequestDispatcher("nav.jsp").forward(request,response);
                request.getRequestDispatcher("manager.jsp").forward(request,response);
            }

        }else {
            response.getWriter().println("失败");

        }
    }
}
